package com.bjsxt.interceptor;

import com.bjsxt.entity.User;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by 苏犇 on 2019/1/6. <br>
 */
public class loginInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = Logger.getLogger(loginInterceptor.class);
    private List<String> excudingUrls;

    public List<String> getExcudingUrls() {
        return excudingUrls;
    }

    public void setExcudingUrls(List<String> excudingUrls) {
        this.excudingUrls = excudingUrls;
    }

    /**
     * This implementation always returns {@code true}.
     *
     * @param request
     * @param response
     * @param handler
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        logger.debug("the request is " + requestUri);
        if (this.excudingUrls.contains(requestUri)) {
            return true;
        }
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            return true;
        } else {
            if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                //如果是ajax请求响应头会有，x-requested-with
                PrintWriter pw = response.getWriter();
                pw.print("<script>top.location.href='/'</script>");
            } else {
                request.getRequestDispatcher("/").forward(request, response);
            }
        }
        return false;
    }

    /**
     * This implementation is empty.
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * This implementation is empty.
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
